import 'dart:async';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/main_delegate.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/share_repository/share_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/mixin/user_stream_mixin.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/change_main_page_event.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/index_nav_page/smart_home_index_nav_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/video_upload_service.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_list_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_one_details_page.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_net_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_upgrade/vg_windows_delegate.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'login/login_and_register_page/login_and_register_page.dart';
import 'login/login_and_register_page/welcome_agree_dialog/welcome_agree_dialog.dart';

/// 整个App首页显示
///
/// @author: zengxiangxi
/// @createTime: 1/4/21 2:35 PM
/// @specialDemand:
class AppMain extends StatefulWidget {

  static const String ROUTER =  "AppMainPage";
  static BuildContext context;

  @override
  _AppMainState createState() => _AppMainState();
}

class _AppMainState extends BaseState<AppMain> with UserStreamMixin{

  ///返回时间
  DateTime _lastPressed;
  bool _isFirst = true;
  StreamSubscription _changeMainPageSubscription;
  String _mainPageTag = IndexNavPage.ROUTER;
  @override
  void initState() {
    super.initState();
    _changeMainPageSubscription = VgEventBus.global.on<ChangeMainPageEvent>().listen((event) {
      if(_mainPageTag == event.tag){
        return;
      }
      print("_mainPageTag:" + _mainPageTag);
      setState(() {
        _mainPageTag = event.tag;
      });
    });

    addUserStreamListen((value) {
      setState(() { });
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      /// 首次安装显示协议弹框
      bool firstInstall = await SharePreferenceUtil.getBool(SP_FIRST_INSTALL);
      if(firstInstall == null && !UserRepository.getInstance().isLogined()){
        await WelcomeAgreeDialog.navigatorPushDialog(context);
      }else{
        /// 初始化友盟
        ConstantRepository.of().initUmeng();
        // ShareRepository.getInstance().submitPrivacyGrantResult(context, null);
      }
      //初始化上传视频相关服务
      VideoUploadService.getInstance();
      //版本更新
      Future.delayed(Duration(milliseconds: 2000),(){
        UpgradeRepository.getInstance(VgNetDelegate.of(false), VgWindowsDelegate.of(),onUpgradeErrorChanged: (UpgradeError error){
          if(StringUtils.isEmpty(error?.message)){
            if(!(error.message.contains("获取升级详情失败"))){
              VgToastUtils.toast(AppMain.context, error?.message);
            }
          }
        }).httpAutoCheckUpgrade();
      });


    });
  }

  @override
  void dispose(){
    MainDelegate.getInstance().dispose();
    _changeMainPageSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    AppMain.context = context;
    return WillPopScope(
        onWillPop: () async {
          print("_mainPageTag4:" + _mainPageTag);
          if(_mainPageTag == IndexNavPage.ROUTER){
            if (_lastPressed == null ||
                DateTime.now().difference(_lastPressed) >
                    Duration(milliseconds: 1500)) {
              toast("再按一次退出");
              _lastPressed = DateTime.now();
              return false;
            } else {
              return true;
            }
          }else{
            if(_mainPageTag == SmartHomeIndexNavPage.ROUTER){
              return true;
            }else{
              VgEventBus.global.send(new ChangeMainPageEvent(SmartHomeIndexNavPage.ROUTER));
              // _mainPageTag =
              // SmartHomeIndexPage.navigatorPush(context);
              return false;
            }
          }
        },
        child: _toMainWidget());
  }


  Widget _toMainWidget(){
    if(UserRepository.getInstance().isLogined()){
      // return IndexNavPage();
      if(UserRepository.getInstance().isSmartHomeCompany()){
          // return SmartHomeIndexNavPage();
          return _judgeIntoWidget();
      }else{
        _mainPageTag = IndexNavPage.ROUTER;
        print("_mainPageTag3:" + _mainPageTag);
        return IndexNavPage();
      }
    }else{
      return LoginAndRegisterPage();
    }

  }


  Widget _judgeIntoWidget(){
    if(StringUtils.isNotEmpty(UserRepository.getInstance().lastshid) && UserRepository.getInstance().tercnt > 0){
      //最后一次浏览的门店有值，需判断进哪个页面
      if(_isFirst){
        //如果是第一次进来，则直接进入详情
        _isFirst = false;
        // _mainPageTag = SmartHomeOneDetailsPage.ROUTER;
        _mainPageTag = SmartHomeStoreDetailsPage.ROUTER;
        print("_mainPageTag0:" + _mainPageTag);
        return SmartHomeStoreDetailsPage(id: UserRepository.getInstance().lastshid,);
      }else{
        //不是第一次
        if(_mainPageTag == SmartHomeIndexNavPage.ROUTER){
          //如果已经包含首页，说明当前就应该在首页
          print("_mainPageTag1:" + _mainPageTag);
          return SmartHomeIndexNavPage(currentPage: 1,);
        }else{
          // _mainPageTag = SmartHomeOneDetailsPage.ROUTER;
          _mainPageTag = SmartHomeStoreDetailsPage.ROUTER;
          print("_mainPageTag2:" + _mainPageTag);
          return SmartHomeStoreDetailsPage(id: UserRepository.getInstance().lastshid,);
        }
      }
    }else{
      if(_isFirst){
        //无最后一次浏览的门店，并且是第一次进门店列表页面
        _isFirst = false;
      }
      _mainPageTag = SmartHomeIndexNavPage.ROUTER;
      int currentPage = 1;
      if(UserRepository.getInstance().tercnt < 1){
        currentPage = 0;
      }
      print("_mainPageTag6:" + _mainPageTag + "," + currentPage.toString());
      return SmartHomeIndexNavPage(currentPage: currentPage,);
    }
  }
}
